package cn.dubnation.org.service.impl;

import cn.dubnation.base.constants.SystemConstants;
import cn.dubnation.base.enums.ResponseCode;
import cn.dubnation.base.exception.BusinessException;
import cn.dubnation.base.service.impl.BaseServiceImpl;
import cn.dubnation.base.util.address.DistanceUtil;
import cn.dubnation.base.util.address.Point;
import cn.dubnation.base.util.audit.ActiveCode;
import cn.dubnation.base.util.audit.BaiduAuditUtils;
import cn.dubnation.base.util.audit.DubnationAssert;
import cn.dubnation.org.domain.Employee;
import cn.dubnation.org.domain.Shop;
import cn.dubnation.org.domain.ShopEmployee;
import cn.dubnation.org.domain.ShopOperateLog;
import cn.dubnation.org.mapper.EmployeeMapper;
import cn.dubnation.org.mapper.ShopEmployeeMapper;
import cn.dubnation.org.mapper.ShopMapper;
import cn.dubnation.org.mapper.ShopOperateLogMapper;
import cn.dubnation.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-12-29
 */
@Service
@Transactional
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired(required = false)
    private ShopMapper shopMapper;

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Autowired(required = false)
    private ShopEmployeeMapper shopEmployeeMapper;

    @Autowired
    private ShopEmployee shopEmployee;

    @Autowired
    private ActiveCode activeCode;

    @Autowired
    private ShopOperateLog shopOperateLog;

    @Autowired(required = false)
    private ShopOperateLogMapper shopOperateLogMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private EmployeeServiceImpl employeeService;


    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    public void settlement(Shop shop) {
        //1.数据校验 (非空校验、格式校验，判断该店铺是否已存在)
        Employee admin = shop.getAdmin();
        DubnationAssert.isEq(admin.getPassword(), admin.getConfirmPassword(), ResponseCode.RESPONSE_CODE_400001);
        Shop shopOfDataBase = shopMapper.queryByName(shop.getName());
        DubnationAssert.isNull(shopOfDataBase, ResponseCode.RESPONSE_CODE_400002);
        //2.数据审核 (店铺名、店铺地址、店铺logo审核)
        List<String> censorText = Arrays.asList(shop.getName(), shop.getAddress());
        List<Map<String, Object>> textCensorMaps = BaiduAuditUtils.textCensor(censorText);
        textCensorMaps.forEach(textCensorMap -> {
            if (!Boolean.valueOf(textCensorMap.get("success").toString())){
                //店铺名称或地址有违禁信息
                throw new BusinessException(textCensorMap.get("message").toString());
            }
        });
//        Map<String, Object> imgCensorMap = BaiduAuditUtils.imgCensor(shop.getLogo());
//        if (!Boolean.valueOf(imgCensorMap.get("success").toString())){
//            //店铺logo存在违禁信息
//            throw new BusinessException(imgCensorMap.get("message").toString());
//        }
        //3.店铺数据入库
        //设置变量值
        shop.setRegisterTime(new Date());
        shop.setState(SystemConstants.Shop.AUDIT);
        Point point = DistanceUtil.getPoint(shop.getAddress());
        shop.setLng(point.getLng());
        shop.setLat(point.getLat());
        shop.setRejectedNum(0);
        shopMapper.insert(shop);
        //4.判断入驻管理员是否已存在, 若已存在则进行店铺关联即可
        Employee employee = employeeMapper.queryByUsername(admin.getUsername());
        if (Objects.isNull(employee)){
            //该入驻员工不存在
            admin.setAge(35);
            admin.setSex(1);
            admin.setState(SystemConstants.Employee.UNAVAILABLE);
            employeeMapper.insert(admin);
            shopEmployee.setEmployeeId(admin.getId());
            activeCode.setEmployeeId(admin.getId());
            shopOperateLog.setOperateId(admin.getId());
            activeCode.setEmployeeId(admin.getId());
        }else {
            //入驻员工存在
            shopEmployee.setEmployeeId(employee.getId());
            activeCode.setEmployeeId(employee.getId());
        }
        //5.店铺和管理员数据关联
        shopEmployee.setShopId(shop.getId());
        shopEmployee.setIsAdmin(SystemConstants.ShopEmployee.IS_ADMIN);
        shopEmployeeMapper.insert(shopEmployee);
        //6.审核通过发送激活邮件
        activeCode.setShopId(shop.getId());
        //TODO 调用发送激活邮件
        redisTemplate.opsForValue().set(SystemConstants.Employee.ACTIVE_CODE, activeCode);
        employeeService.sendPassEmail(shop);
        //7.记录店铺入驻日志
        shopOperateLog.setShopId(shop.getId());
        shopOperateLog.setOperateTime(new Date());
        shopOperateLog.setOperateType(SystemConstants.ShopOperateLog.SETTLE_IN);
        shopOperateLog.setNote("店铺入驻");
        shopOperateLogMapper.insert(shopOperateLog);
    }

    /**
     * 审核店铺数据
     * @param shop
     */
    @Override
    public void audit(Shop shop) {
        StringBuilder errMsg = new StringBuilder(); //返回的错误信息拼接
        //审核文本
        List<String> textAuditList = Arrays.asList(shop.getName(), shop.getAddress());
        List<Map<String, Object>> textCensorList = BaiduAuditUtils.textCensor(textAuditList);
        textCensorList.forEach(textCensor -> {
            if (!Boolean.valueOf(textCensor.get("success").toString())){
                errMsg.append(textCensor.get("message").toString());
            }
        });
        //审核图片
//        Map<String, Object> imgCensor = BaiduAuditUtils.imgCensor(shop.getLogo());
//        if (!Boolean.valueOf(imgCensor.get("success").toString())){
//            String imgErrMessage = imgCensor.get("message").toString();
//            if (errMsg.length() > 0){
//                errMsg.append("," + imgErrMessage);
//            }else {
//                errMsg.append(imgErrMessage);
//            }
//        }
        //审核地址是否符合规范
        Double lng = shop.getLng();
        Double lat = shop.getLat();
        if (lng == null || lat == null){
            Point point = DistanceUtil.getPoint(shop.getAddress());
            Double lng1 = point.getLng();
            Double lat1 = point.getLat();
            if (!((lng1 >= 0.00 && lng1 <= 180.00) || (lat1 >= 0.00 && lat1 <= 90.00))){
                if (errMsg.length() > 0){
                    errMsg.append("," + ResponseCode.RESPONSE_CODE_400004.getMessage());
                }else {
                    errMsg.append(ResponseCode.RESPONSE_CODE_400004.getMessage());
                }
            }
        }else {
            if (!((lng >= 0.00 && lng <= 180.00) || (lat >= 0.00 && lat <= 90.00))){
                if (errMsg.length() > 0){
                    errMsg.append("," + ResponseCode.RESPONSE_CODE_400004.getMessage());
                }else {
                    errMsg.append(ResponseCode.RESPONSE_CODE_400004.getMessage());
                }
            }
        }
        if (!(errMsg.equals("") || errMsg.equals(null))){
            //有错误信息
            throw new BusinessException(errMsg.toString());
        }
    }

    /**
     * 激活账户
     * @param code
     */
    @Override
    public void active(String code) {
        ActiveCode activeCode = (ActiveCode) redisTemplate.opsForValue().get(code);
        //修改店铺状态为激活成功, 员工状态为可用
        Shop shop = shopMapper.queryById(activeCode.getShopId());
        Employee employee = employeeMapper.queryById(activeCode.getEmployeeId());
        shop.setState(SystemConstants.Shop.ACTIVATED);
        shopMapper.update(shop);
        employee.setState(SystemConstants.Employee.AVAILABLE);
        employeeMapper.update(employee);
        shopOperateLog.setShopId(activeCode.getShopId());
        shopOperateLog.setOperateId(activeCode.getEmployeeId());
        shopOperateLog.setOperateType(SystemConstants.ShopOperateLog.ACTIVATED);
        shopOperateLog.setNote("店铺已激活");
        shopOperateLog.setOperateTime(new Date());
    }
}
